<template>
  <div class="product">
    <div class="a-side">
      <div class="header">
        <div class="a-side-title">资讯分类</div>
        <div class="a-side-add" @click="handleRowUpdate('add')">
          <i class="el-icon-circle-plus-outline"></i>
          <span>新增</span>
        </div>
      </div>
      <el-input
        v-model="filterText"
        placeholder="输入关键字进行过滤"
        size="small"
        clearable
        class="a-side-input"
      >
      </el-input>
      <el-tree
        ref="tree"
        v-loading="treeLoading"
        node-key="id"
        :data="modelTree"
        :default-expand-all="true"
        :filter-node-method="filterNode"
        :expand-on-click-node="false"
      >
        <span slot-scope="{ data }" class="custom-tree-node">
          <span
            class="node-label"
            :class="{ active: customQuery.classificationId === data.id }"
            @click="handleRowChange(data)"
          >
            {{ data.nameZh }}
          </span>
          <span>
            <el-button
              type="text"
              size="small"
              icon="el-icon-edit"
              @click="() => handleRowUpdate('edit', data)"
            >
            </el-button>
            <el-button
              type="text"
              size="small"
              icon="el-icon-delete"
              @click="() => handleRowDelete(data)"
            >
            </el-button>
          </span>
        </span>
      </el-tree>
    </div>
    <div class="content">
      <div class="scroll">
        <hzhy-data-table ref="dataTable" v-bind="tableConfigTask" :customQuery.sync="customQuery">
          <template slot="left-btn">
            <el-button
              type="primary"
              icon="el-icon-plus"
              plain
              @click="handleProductRowUpdate('add')"
            >
              添加
            </el-button>
          </template>
        </hzhy-data-table>
      </div>
    </div>
    <common-dialog-form
      ref="commonDrawerForm"
      :visible.sync="visible"
      :title="drawerTitle"
      :content="formContent"
      :onConfirm="onConfirm"
    ></common-dialog-form>
    <common-dialog-form
      ref="commonProductForm"
      :visible.sync="productVisible"
      :title="drawerTitle"
      :content="productFormContent"
      :onConfirm="onProductConfirm"
    ></common-dialog-form>
  </div>
</template>

<script>
import CommonDialogForm from '@/components/common-dialog-form'
import CommonUploadFile from '@/components/common-upload-file'
import SelfPageSelect from '@/container/configure/component/self-page-select'

import * as api from '@/const/api'
import { configureSelfPageEdit } from '@/const/path'

export default {
  title: '新闻资讯',
  name: 'ConfigureNews',
  components: {
    CommonDialogForm,
  },
  data() {
    return {
      visible: false,
      productVisible: false,
      currentRow: {},
      filterText: '',
      treeLoading: false,
      modelTree: [],
      customQuery: {
        solutionClassificationType: 3,
      },
    }
  },
  computed: {
    // 编辑还是新增
    isEdit() {
      return !!this.currentRow.id
    },
    // 侧边栏表单标题
    drawerTitle() {
      return this.isEdit ? '编辑' : '新增'
    },
    tableConfigTask() {
      return {
        url: api.solutionPage,
        columns: [
          {
            label: '序号',
            type: 'index',
            prop: 'index',
          },
          {
            label: '资讯分类',
            prop: 'classificationId',
            formatter: ({ classificationId }) => {
              const item = this.modelTree.find(({ id }) => id === classificationId)
              return item ? item.nameZh : ''
            },
          },
          {
            label: '标题(名称)',
            prop: 'titleZh',
            minWidth: 120,
          },
          {
            label: '标题(英文)',
            prop: 'titleEn',
            minWidth: 120,
          },
          {
            label: '副标题(中文)',
            prop: 'subtitleZh',
            minWidth: 120,
          },
          {
            label: '副标题(英文)',
            prop: 'subtitleEn',
            minWidth: 120,
          },
          {
            label: '封面图',
            prop: 'coverImage',
            minWidth: 120,
            formatter: ({ coverImage }) => {
              if (!coverImage) {
                return ''
              }

              return (
                <img
                  src={coverImage}
                  onClick={() => window.open(coverImage)}
                  style="cursor: pointer;max-width: 60px;height:32px;display: block;"
                />
              )
            },
          },
          {
            label: '链接地址',
            prop: 'url',
            formatter: ({ url }) => {
              if (!url) {
                return '--'
              }

              return (
                <span style="cursor: pointer;color: #006fff" onClick={() => this.handleConfig(url)}>
                  查看链接
                </span>
              )
            },
          },
          {
            label: '是否启用',
            prop: 'enable',
            formatter: ({ enable }) => (enable === 1 ? '启用' : '禁用'),
          },
          {
            label: '置顶首页',
            prop: 'topShow',
            formatter: ({ topShow }) => (topShow === 1 ? '是' : '否'),
          },
          {
            label: '操作',
            prop: 'operation',
            width: 160,
            fixed: 'right',
            setBtns: (row) => {
              const btns = [
                {
                  label: '编辑',
                  handler: () => {
                    this.handleProductRowUpdate('edit', row)
                  },
                },
                {
                  label: row.topShow === 1 ? '取消置顶' : '置顶',
                  handler: () => {
                    this.handleRowTopUpdate(row)
                  },
                },
                {
                  label: '删除',
                  className: 'red',
                  handler: () => {
                    this.handleProductRowDelete(row)
                  },
                },
              ]
              return this.$ac.operationAccess(btns)
            },
          },
        ],
        searchForm: [
          {
            $type: 'input',
            $id: 'titleZh',
            label: '标题',
            $el: {
              clearable: true,
              placeholder: '请输入',
            },
          },
          {
            $type: 'select',
            $id: 'topShow',
            label: '是否置顶',
            $options: [
              {
                label: '是',
                value: '1',
              },
              {
                label: '否',
                value: '0',
              },
            ],
            $el: {
              clearable: true,
              placeholder: '请选择',
            },
          },
        ],
      }
    },
    formContent() {
      return [
        {
          $id: 'nameZh',
          $type: 'input',
          label: '资讯分类(中文)',
          $el: {
            placeholder: '请输入资讯分类(中文)',
            clearable: true,
            maxlength: 50,
            showWordLimit: true,
          },
          rules: [{ required: true, message: '请输入资讯分类(中文)', trigger: 'change' }],
        },
        {
          $id: 'nameEn',
          $type: 'input',
          label: '资讯分类(英文)',
          $el: {
            placeholder: '请输入资讯分类(英文)',
            clearable: true,
            maxlength: 50,
            showWordLimit: true,
          },
          rules: [{ required: true, message: '请输入资讯分类(英文)', trigger: 'change' }],
        },
        {
          $id: 'sort',
          $type: 'input',
          label: '排序',
          $el: {
            type: 'number',
            placeholder: '请输入排序',
            maxLength: 20,
            clearable: true,
          },
        },
      ]
    },
    productFormContent() {
      return [
        {
          $id: 'classificationId',
          $type: 'select',
          label: '资讯分类',
          $el: {
            placeholder: '请输入资讯分类',
            clearable: true,
          },
          remote: {
            url: `${api.classificationPage}`,
            params: {
              type: 3,
            },
            methods: 'post',
            dataPath: 'data.data',
            label: 'nameZh',
            value: 'id',
          },
          rules: [{ required: true, message: '请输入资讯分类', trigger: 'change' }],
        },
        {
          $id: 'url',
          label: '链接地址',
          component: SelfPageSelect,
        },

        {
          $id: 'titleZh',
          $type: 'input',
          label: '标题(中文)',
          $el: {
            placeholder: '请输入标题(中文)',
            clearable: true,
            maxlength: 200,
            showWordLimit: true,
          },
          rules: [{ required: true, message: '请输入标题(中文)', trigger: 'change' }],
        },
        {
          $id: 'titleEn',
          $type: 'input',
          label: '标题(英文)',
          $el: {
            placeholder: '请输入标题(英文)',
            clearable: true,
            maxlength: 200,
            showWordLimit: true,
          },
          rules: [{ required: true, message: '请输入标题(英文)', trigger: 'change' }],
        },
        {
          $id: 'subtitleZh',
          $type: 'input',
          label: '副标题(中文)',
          $el: {
            type: 'textarea',
            placeholder: '请输入副标题(中文)',
            clearable: true,
            maxlength: 1000,
            rows: 7,
            showWordLimit: true,
          },
        },
        {
          $id: 'subtitleEn',
          $type: 'input',
          label: '副标题(英文)',
          $el: {
            type: 'textarea',
            placeholder: '请输入副标题(英文)',
            clearable: true,
            maxlength: 1000,
            rows: 7,
            showWordLimit: true,
          },
        },
        {
          $id: 'enable',
          $type: 'switch',
          label: '启用标志',
          $el: {
            activeValue: 1,
            inactiveValue: 0,
          },
        },
        {
          $id: 'topShow',
          $type: 'switch',
          label: '是否置顶',
          $el: {
            activeValue: 1,
            inactiveValue: 0,
          },
        },
        {
          component: CommonUploadFile,
          $id: 'coverImage',
          label: '封面图片',
          $el: {
            max: 1,
            accept: '.jpg,.jpeg,.png',
            tips: '图片最佳尺寸：240 X 240',
          },
          inputFormat: ({ coverImage }) => {
            if (!coverImage) {
              return []
            }
            const result = []
            coverImage.split(',').forEach((item) => {
              result.push({
                name: item,
                response: item,
              })
            })
            return result
          },
          outputFormat: (val) => {
            if (!val || !val.length) {
              return
            }
            return val.map(({ response }) => response).join(',')
          },
        },
      ]
    },
  },
  mounted() {
    this.goClassification()
  },
  methods: {
    // 获取分类数据
    async goClassification() {
      try {
        const params = {
          type: 3,
        }
        const { code, msg, data } = await this.$axios.$post(api.classificationPage, params)
        if (+code !== 200) {
          throw new Error(msg || '操作失败')
        }
        this.modelTree = data || []
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    // 侧边栏form确认回调
    async onConfirm(data) {
      try {
        const params = {
          ...data,
          type: 3,
        }
        // 编辑需要加上id参数
        if (this.isEdit) {
          params.id = this.currentRow.id
        }

        let res = ''

        if (this.isEdit) {
          res = await this.$axios.$put(api.classification, params)
        } else {
          res = await this.$axios.$post(api.classification, params)
        }

        const { code, msg } = res
        if (+code !== 200) {
          throw new Error(msg || '操作失败')
        }

        this.$message.success('操作成功')
        this.goClassification()
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    async onProductConfirm(data) {
      try {
        const params = {
          ...data,
        }
        // 编辑需要加上id参数
        if (this.isEdit) {
          params.id = this.currentRow.id
        }

        let res = ''

        if (this.isEdit) {
          res = await this.$axios.$put(api.solution, params)
        } else {
          res = await this.$axios.$post(api.solution, params)
        }

        const { code, msg } = res
        if (+code !== 200) {
          throw new Error(msg || '操作失败')
        }
        this.$message.success('操作成功')
        this.$refs.dataTable.goPage()
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    handleRowTopUpdate(row) {
      const topData = {
        ...row,
        topShow: row.topShow === 1 ? 0 : 1,
      }

      delete topData.updateTime
      delete topData.createTime
      delete topData.tIndex

      this.currentRow = { ...row }
      this.onProductConfirm({ ...topData })
    },
    // 打开侧边栏form弹层
    handleRowUpdate(type, row) {
      this.visible = true
      if (type === 'edit') {
        this.currentRow = row
        this.$refs.commonDrawerForm.updateForm(row)
      } else {
        this.currentRow = {}
      }
    },
    // 打开侧边栏form弹层
    handleProductRowUpdate(type, row) {
      this.productVisible = true
      if (type === 'edit') {
        this.currentRow = row
        this.$refs.commonProductForm.updateForm(row)
      } else {
        this.currentRow = {}
        this.$refs.commonProductForm.updateForm({
          enable: 1,
        })
      }
    },
    async handleRowDelete(row) {
      let loading = ''
      try {
        const isFlag = await this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        if (isFlag !== 'confirm') {
          return
        }
        loading = this.$loading({
          text: 'Loading',
          spinner: 'el-icon-loading',
        })
        const { code, msg } = await this.$axios.$delete(api.deleteClassification(row.id))
        if (+code !== 200) {
          throw new Error(msg || '操作失败')
        }
        this.$message.success('操作成功')
        this.goClassification()
      } catch (err) {
        err.message && this.$message.error(err.message)
      } finally {
        loading && loading.close()
      }
    },
    async handleProductRowDelete(row) {
      let loading = ''
      try {
        const isFlag = await this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        if (isFlag !== 'confirm') {
          return
        }
        loading = this.$loading({
          text: 'Loading',
          spinner: 'el-icon-loading',
        })
        const { code, msg } = await this.$axios.$delete(`${api.solution}/${row.id}`)
        if (+code !== 200) {
          throw new Error(msg || '操作失败')
        }
        this.$message.success('操作成功')
        this.$refs.dataTable.goPage()
      } catch (err) {
        err.message && this.$message.error(err.message)
      } finally {
        loading && loading.close()
      }
    },
    handleRowChange(row) {
      if (this.customQuery.classificationId === row.id) {
        this.$set(this.customQuery, 'classificationId', '')
      } else {
        this.$set(this.customQuery, 'classificationId', row.id)
      }
      this.$refs.dataTable.goPage(1)
    },
    handleConfig(id) {
      this.$router.push({
        path: `${configureSelfPageEdit}${id}?type=edit`,
      })
    },
    filterNode(value, data) {
      if (!value) {
        return true
      }
      return data.factoryName.includes(value)
    },
  },
}
</script>

<style lang="less" scoped>
@import '~assets/var';

.product {
  width: 100%;
  height: 100%;
  display: flex;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .a-side {
    flex: 0 0 280px;
    border-right: 1px solid #e4e8f3;
    padding: 15px 10px 0 15px;

    .a-side-title {
      display: flex;
      align-items: center;

      &::before {
        display: block;
        content: ' ';
        width: 4px;
        height: 12px;
        background-color: #575962;
        border-radius: 3px;
        margin-right: 6px;
      }
    }

    .a-side-add {
      cursor: pointer;
    }

    .a-side-input {
      margin: 15px 0;
    }

    :deep(.el-tree) {
      height: calc(100% - 80px);
      overflow: auto;

      .custom-tree-node {
        display: flex;
        flex: 1;
        justify-content: space-between;
        align-items: center;
        font-size: 14px;

        i {
          color: @breadcrumb-color;
          font-size: 14px;
        }

        .node-label {
          flex: 1;

          &.active {
            color: #435fba;
            font-weight: bold;
          }
        }
      }
    }
  }

  .content {
    flex: 1;
    padding-left: 20px;
    overflow: hidden;

    .scroll {
      width: 100%;
      height: 100%;
      overflow: auto;
    }
  }
}
</style>
